package com.relatev.minecraft.TRMobAPI;

import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

public class ItemStackJsonDeserializer implements JsonDeserializer<ItemStack> {

    private static Gson gson = new Gson();

    @Override
    public ItemStack deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException {
        JsonElement metajson = je.getAsJsonObject().get("meta");
        je.getAsJsonObject().remove("meta");
        ItemStack item = gson.fromJson(je, type);
        ItemMeta im = item.getItemMeta();
        if (metajson != null) {
            for (Entry<String, JsonElement> metaen : metajson.getAsJsonObject().entrySet()) {
                try {
                    Field field = im.getClass().getDeclaredField(metaen.getKey());
                    field.setAccessible(true);
                    field.set(im, gson.fromJson(metaen.getValue(), field.getType()));
                } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
                    Logger.getLogger(ItemStackJsonDeserializer.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return item;
    }

}
